<template>
  <div class="station-map">
    <div id="container" class="map-wrap"></div>
    <div v-if="data.address" class="text">
      <div class="iconfont icon-station-map"></div>
      当前定位：{{ data.address }}（{{ data.lng }}/{{ data.lat }}）
    </div>
  </div>
</template>

<script lang="ts" setup>
import AMapLoader from '@amap/amap-jsapi-loader';
import makerImg from '@/assets/images/station-icon.png';

const proxy: any = getCurrentInstance()?.proxy;

const data = reactive({
  aMap: null as any,
  map: null as any,
  geocoder: null as any,
  tempMarker: null as any,
  markerIcon: null as any,
  lng: proxy.$config.lng,
  lat: proxy.$config.lat,
  address: '',
});

const emit = defineEmits(['set-location', 'set-region']);

(window as any)._AMapSecurityConfig = {
  securityJsCode: proxy.$config.securityJsCode,
};
AMapLoader.load({
  key: proxy.$config.key, // 申请好的Web端开发者Key，首次调用 load 时必填
  version: '1.4.15', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
  plugins: ['AMap.Geocoder'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
  AMapUI: {
    // 是否加载 AMapUI，缺省不加载
    version: '1.1', // AMapUI 缺省 1.1
    plugins: [], // 需要加载的 AMapUI ui插件
  },
  Loca: {
    // 是否加载 Loca， 缺省不加载
    version: '1.3.2', // Loca 版本，缺省 1.3.2
  },
})
  .then((AMap: any) => {
    data.aMap = AMap;
    data.map = new data.aMap.Map('container', {
      zoom: 11, //级别
      center: [data.lng, data.lat], //中心点坐标
      viewMode: '3D', //使用3D视图
    });

    const size = new data.aMap.Size(30, 35);
    data.markerIcon = new data.aMap.Icon({
      size: size,
      image: makerImg,
      imageSize: size,
    });

    data.geocoder = new data.aMap.Geocoder({ radius: 1000, extensions: 'all' });

    data.map.on('click', (e: any) => {
      console.log('eeee======', e);
      // 获取当前经纬度
      data.lng = e.lnglat.getLng();
      data.lat = e.lnglat.getLat();
      addMarker(data.lng, data.lat);
      emit('set-location', data.lng, data.lat);
    });

    // addMarker();
  })
  .catch((e: any) => {
    console.log(e);
  });

onDeactivated(() => {
  data.aMap && data.aMap.destroy();
  data.aMap = null;
});
// 添加覆盖物
const addMarker = (lng: any, lat: any) => {
  clearMarker();
  data.lng = lng;
  data.lat = lat;
  data.tempMarker = new data.aMap.Marker({
    icon: data.markerIcon,
    position: [lng, lat],
    offset: new data.aMap.Pixel(-15, -35),
    draggable: true,
  });
  data.tempMarker.setMap(data.map);
  data.map.panTo(new data.aMap.LngLat(lng, lat));
  parseLngLat();
};

// 清除覆盖物
const clearMarker = () => {
  if (data.tempMarker) {
    data.map.remove(data.tempMarker);
  }
};

//地址获取坐标
const parseAddress = (address: string) => {
  return new Promise((resolve) => {
    data.geocoder.getLocation(address, (status: any, result: any) => {
      console.log(status, result);
      if (status === 'complete' && result.info === 'OK') {
        data.lng = result.geocodes[0].location.lng;
        data.lat = result.geocodes[0].location.lat;
        addMarker(data.lng, data.lat);
        resolve({ lng: data.lng, lat: data.lat });
      } else {
        ElMessage({
          message: '定位失败',
          type: 'warning',
        });
      }
    });
  });
};

//坐标获取地址
const parseLngLat = () => {
  data.geocoder.getAddress([data.lng, data.lat], (status: any, result: any) => {
    console.log('res------', status, result);
    if (status === 'complete' && result.info === 'OK') {
      data.address = result.regeocode.formattedAddress;
      const info = result.regeocode.addressComponent;
      const obj = {
        code: info.adcode,
        name: `${info.province}${info.city || info.province}${info.district}`,
      };
      emit('set-region', obj);
    } else {
      emit('set-region', null);
    }
  });
};

const setMarker = (lng: any, lat: any) => {
  data.lng = lng;
  data.lat = lat;
  const timer = setTimeout(() => {
    data.tempMarker = new data.aMap.Marker({
      icon: data.markerIcon,
      position: [lng, lat],
      offset: new data.aMap.Pixel(-15, -35),
      draggable: true,
    });
    data.tempMarker.setMap(data.map);
    data.map.panTo(new data.aMap.LngLat(lng, lat));
    clearTimeout(timer);
  }, 500);
};

defineExpose({
  parseAddress,
  setMarker,
});
</script>

<style lang="scss">
.station-map {
  .map-wrap {
    width: 660px;
    height: 400px;
  }
  .text {
    display: flex;
    margin-top: 6px;
    line-height: 15px;
    color: #555;
    font-size: 10px;

    .iconfont {
      margin-right: 5px;
      font-size: 16px;
      color: #b3c1f6;
    }
  }
}
</style>